package ru.amse.stroganova.presentation;

import java.util.HashMap;
import java.util.Map;

/**
 * This class presents a way to convert different presentation types to each other.
 * 
 * @author Dasha Stroganova
 *
 */
//TODO after creating interfaces for UI move this class to converter package
public class PresentationConverter {
	
	/**
	 * Converts unweighted presentation to weighted.
	 * 
	 * @param presentation
	 * @return converted presentation
	 */
	public static GraphPresentation convertToWeighted(GraphPresentation presentation) {
		GraphPresentation copyPres = new GraphPresentation(presentation.isDirected(), true);
		copyPresentation(presentation, copyPres, presentation.isDirected(), true);
		return copyPres;
		
	}
	
	/**
	 * Converts weighted presentation to unweighted.
	 * 
	 * @param presentation
	 * @return converted presentation
	 */
	public static GraphPresentation convertToUnweighted(GraphPresentation presentation) {
		GraphPresentation copyPres = new GraphPresentation(presentation.isDirected(), false);
		copyPresentation(presentation, copyPres, presentation.isDirected(), false);
		return copyPres;
	}
	
	/**
	 * Converts directed presentation to undirected.
	 * 
	 * @param presentation
	 * @return converted presentation
	 */
	public static GraphPresentation convertToUndirected(GraphPresentation presentation) {
		GraphPresentation copyPres = new GraphPresentation(false, presentation.isWeighted());
		copyPresentation(presentation, copyPres, false, presentation.isWeighted());
		return copyPres;
	}
	
	private static void copyPresentation(GraphPresentation originalPres, GraphPresentation copyPres, boolean isDirected, boolean isWeighted) {
		Map<VertexPresentation, VertexPresentation> copyVertices = new HashMap<VertexPresentation, VertexPresentation>();
		for (VertexPresentation vp : originalPres.getVertexPresentations()) {
			VertexPresentation copyVP = new VertexPresentation(vp.getCenter());
			copyPres.addVertex(copyVP);
			copyVertices.put(vp, copyVP);
		}
		for (EdgePresentation ep : originalPres.getEdgePresentations()) {
			VertexPresentation copySource = copyVertices.get(originalPres.getPresentationForVertex(ep.getEdge().getSource()));
			VertexPresentation copyDestin = copyVertices.get(originalPres.getPresentationForVertex(ep.getEdge().getDestination()));
			if (copyPres.areConnected(copySource, copyDestin)) {
				copyPres.getGraph().getConnectingEdge(copySource.getVertex(), copyDestin.getVertex()).setWeight(ep.getWeight());
			} else {
				EdgePresentation copyEP = new EdgePresentation(copySource, copyDestin, isDirected, isWeighted);
				copyEP.setWeight(ep.getWeight());
				copyPres.addEdge(copyEP);
			}
		}
	}
}
